var T = (function(window,undefined){
    function isArray(v){
        return Object.prototype.toString.call(v) === '[object Array]'
    }

    function template(str, data) {
        return str.replace(/\{ *([\w_]+) *\}/g, function (str, key) {
            var value = data[key];
            if (value === undefined) {
                console.log('No value provided for variable ' + str);
                value = "{" + key + "}";
            } else if (typeof value === 'function') {
                value = value(data);
            }
            return value;
        })
    }


    var wx_config = {
        appid: '',
        img_url: document.baseURI.replace(/(index\.html|\?.*|\#.*)/g,"") +"assets/res/share.jpg",
        img_width: '300',
        img_height: '300',
        link: location.origin + location.pathname,
        desc: '吴廷和鲁麦梅',//\n\n红权科技技术支持
        title: '我们结婚了'
    };

    function share_wx(img,title,desc){

        img && (wx_config.img_url = img);
        title && (wx_config.title = title);
        desc && (wx_config.desc = desc);

        console.log(wx_config);
    }

    function load(v){

        var head = document.getElementsByTagName("head")[0];

        if(!isArray(v)) v = [v];

        for(var i=0;i<v.length;i++){
            var t = v[i], s;
            if(/\.js/.test(t)) {
                s = document.createElement("script");
                s.type = "text/javascript";
                s.src = t;
            }
            else if(/\.css/.test(t)){
                s = document.createElement("link");
                s.rel = "stylesheet";
                s.type = "text/css";
                s.href = t;
            }
            head.appendChild(s);
        }
    }

    function zeroize(v){
        return v<10 ? "0"+v : v;
    }
    function format_date(v,fmt){
        var d = v===null ? new Date() : new Date(v);
        return fmt.replace(/(?:d{1,2}|w|M{1,3}|yy(?:yy)?)/g, function(str) {

            switch(str) {

                case 'd':	return d.getDate();

                case 'dd':	return zeroize(d.getDate());

                case 'w':	return ['Sun','Mon','Tue','Wed','Thr','Fri','Sat'][d.getDay()];

                case 'M':	return d.getMonth() + 1;

                case 'MM':	return zeroize(d.getMonth() + 1);

                case 'MMM':	return ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'][d.getMonth()];

                case 'yy':	return String(d.getFullYear()).substr(2);

                case 'yyyy':	return d.getFullYear();

                default:	return $0.substr(1, $0.length - 2);

            }

        });
    }

    document.addEventListener('WeixinJSBridgeReady', function () {

        var WJ = WeixinJSBridge;
        // 发送给好友
        WJ.on('menu:share:appmessage', function () {

            WJ.invoke('sendAppMessage', wx_config, function (res) {
                _report('sendAppMessage', res.err_msg);
            });

        });
        // 发送到朋友圈
        WJ.on('menu:share:timeline', function () {
            WJ.invoke('shareTimeline', wx_config, function (res) {
                _report('shareTimeline', res.err_msg);
            });

        });

        // 发送到微博
        WJ.on('menu:share:weibo', function () {
            WJ.invoke('sendAppMessage', wx_config, function (res) {
                _report('sendAppMessage', res.err_msg);
            });
        });
    });

    return {
        'template' : template,
        'load' : load,
        'format_date':format_date,
        'share_wx':share_wx
    }
}(window,undefined));


var sounder = (function(){

    function create(tag, id, cls, parent, style, data) {
        var el = document.createElement(tag);
        if (id) el.id = id;
        if (cls) el.className = cls;
        if (style) el.setAttribute("style", style);
        if (data) {
            for (var key in data)
                el.setAttribute(key, data[key]);
        }
        if (parent) parent.appendChild(el);
        return el;
    }

    var bind = function (fn, obj) {
        var args = arguments.length > 2 ? Array.prototype.slice.call(arguments, 2) : [];
        return function () {
            return fn.apply(obj, args.concat(Array.prototype.slice.call(arguments)));
        };
    };

    var touch = ("ontouchstart" in document.documentElement),
        mobile = (typeof orientation !== undefined + '');


    var Sound = function(el , opts){
        this.opts = opts = opts || {};
        this.sources =
            (Object.prototype.toString.call(opts.sources) !== '[object Array]') ?
                [opts.sources] :
                opts.sources;
        this.container = el;
        this.count = this.sources.length;
        this._init();
    };


    Sound.prototype = {
        list: {},
        container: null,
        index: -1,
        count: 1,
        audio: null,

        _init: function () {

            this.audio = create("audio", null, null, this._container, "");
            this.audio.addEventListener("ended", bind(this._onNext, this));

            if(this.opts.autoplay == true) {
                if (mobile) {
                    var self = this;;
                    var ap = function(){
                        self.play();
                        document.body.removeEventListener('touchstart', ap);
                    }
                    document.body.addEventListener('touchstart', ap);

                } else {

                    this.play(0);
                }
            }


        }
        ,
        _onNext: function () {

            var n = this.index + 1
            if(n > this.count){
                if(this.opts.repeat == -1){
                    this.play(0);
                }
            }else{
                this.play(n);
            }

        },

        play: function (index) {
            if (arguments.length == 0) index = 0;

            if (index != this.index) {
                if (index > this.count) return;
                this.index = index;
                this.audio.src = this.sources[index].url;
                this.audio.play();
            }
        },


        stop: function (id) {
            this.audio.stop();
        },
        pause: function (id) {
            this.audio.pause();
        },

        toggle: function () {
            if (this.audio.paused) {
                this.audio.play();
            } else {
                this.audio.pause();
            }

            return !this.audio.paused;
        }
    }

    var _$ = window.jQuery || window.Zepto || window.$;
    if(_$){

        (function($){
            $.fn.sounder = function(opts){
                return new Sound($(this)[0]  , opts);
            }
        })(_$);
    }

    return function(el , opts){
        return new Sound(document.getElementById(el)  , opts);
    }
}());


var app = {
    set:function(){
        var name = $('#j-name').val();
        var content = $('#j-content').val();
        if(!name){
            alert('who are you?');return;
        }
        if(!content){
            alert('说点什么呗.');return;
        }
        $.post('api/?m=wedding&a=creat',{
            'name':name,
            'content':content,
            'date':T.format_date(null,'yyyy-MM-dd')
        } , function(d){
            if(d.status == '0'){
                alert("留言成功");
            }else{
                alert("留言失败");
            }
        },'json');

    },

    get:function(){
        var tpl = $(".js-tpl").html();
        $.getJSON('api/?m=wedding&a=index&callback=?',function(data){
            $(".m-list").html('');
            for(var i= 0,l= data.length;i<l;i++){
                //console.log(T.format_date(data[i].create_time,'yyyy-MM-dd'))
                data[i].date = data[i].date.split(' ')[0];//T.format_date(data[i].date,'yyyy-MM-d');
                $(".m-list").append(T.template( tpl , data[i]) );
            }

            $(".u-st li:eq(0) i").html(data.length);
            //$(".u-st li:eq(1) i").html(data.length);

        })
    }
    ,
    render : function(){

    }
}

$(function() {
    $('#main').fullpage({
        'verticalCentered': false,
        'css3': true,
        'anchors':['p0','p1','p2','p3','p4','p5','p6','p7','p8'],
        'resize':false,
        'afterLoad': function(anchorLink, index){
            $('#pageNum i').html(index);
            if(index==7) {
                $('#arw').addClass('arwDown');
                $('#arw').removeClass('arwUp');
            }
            else {
                $('#arw').removeClass('arwDown');
                $('#arw').addClass('arwUp');
            }
        },

        'onLeave': function(index, nextIndex, direction){

        }
    });


    var h = $(document.body).height(), w = $(document.body).width(), scale = w/h;
    if(h < 490 || scale>0.7){
        $(document.body).addClass("fx1");
    }

    // 总高度 - 图片高度 - margin-top(6%) - margin(2*5%) - 底部
    var list_h = h - $(".u-wall .header").height() - h * .16 - 86;
    //console.log("list height: "+list_h);
    $(".m-list").height(list_h - 5);

    var evt = ("ontouchstart" in document.body) ? 'touchstart' : 'click';

    $('.u-btn-wall').on(evt , function(){
        $(".u-wall").addClass("show");
        app.get();
        $.fn.fullpage.setAllowScrolling(false);
    });

    $('.u-btn').on(evt , function(){
        app.set();
    });

    $('.u-back').on(evt , function(){
        $(".u-wall").removeClass("show");
        $.fn.fullpage.setAllowScrolling(true);
    })

    sounder(document.body,{
        sources:{url:'assets/res/bg.mp3'},
        repeat:-1,
        autoplay:true
    });

    $('.p1 .heart').on(evt , function(){
        $.fn.fullpage.moveSectionDown();
    });
    T.share_wx(null,'我们结婚啦','吴廷 & 鲁麦梅 的喜帖');
});

